<?php

/**
 * Error组件
 *
 * @author edikud
 * @package Widget
 * @copyright Copyright (c) 2019 Cola (http://www.mcooo.com)
 * @license GNU General Public License 2.0
 */
class Widget_Error extends Cola
{
    /**
     * Sends an HTTP 500 response for any errors.
     *
     * @param object $e Thrown exception
     */
    public function set($e) 
	{
		// 插件接口
		//HOOK {$plugged} PLUG_Error($e, $this);
		
        if ($plugged) {
            return ;
        }
		
        $isException = is_object($e);
        $message = '';

        if ($isException) {
            $code = $e->getCode();
            $message = $e->getMessage();
        } else {
            $code = $e;
        }

        $charset = Common::$charset;

        if ($isException && $e instanceof Db_Exception) {
            $code = 500;

            //覆盖原始错误信息
            $message = 'Database Server Error';

            if ($e instanceof Db_Exception) {
                $code = 503;
                $message = 'Error establishing a database connection';
            } else if ($e instanceof Db_Builder_Exception) {
                $message = 'Database Query Error';
            }
        } else {
            switch ($code) {
                case 500:
                    $message = 'Server Error';
                    break;

                case 404:
                    $message = 'Page Not Found';
                    break;

                default:
                    $code = 'Error';
                    break;
            }
        }
		
		$message = nl2br($message);
		
$msg = '
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="' . $charset . '">
        <title>'. $code .'</title>
        <style>
            html {
                padding: 50px 10px;
                font-size: 16px;
                line-height: 1.4;
                color: #666;
                background: #F6F6F3;
                -webkit-text-size-adjust: 100%;
                -ms-text-size-adjust: 100%;
            }

            html,
            input { font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; }
            body {
                max-width: 500px;
                _width: 500px;
                padding: 30px 20px;
                margin: 0 auto;
                background: #FFF;
            }
            ul {
                padding: 0 0 0 40px;
            }
            .container {
                max-width: 380px;
                _width: 380px;
                margin: 0 auto;
            }
        </style>
    </head>
    <body>
        <div class="container">
            '.$message.'
        </div>
    </body>
</html>';
        try {
            $this->response
                ->status($e->getCode())
                ->write($msg)
                ->send();
        } catch (Throwable $t) {
            exit($msg);
        }catch (Exception $ex) {
            exit($msg);
        }
    }
}
